import { defineStore } from "pinia";
import { ref } from "vue";
import { post } from "@/utils/http";
import cookies from 'js-cookie'
import { ElMessage, ElMessageBox } from 'element-plus'


export const useUserInfoStore = defineStore('userInfo', () => {
    //用户信息
    let userInfo = ref({} as UserInfo)
    //登录信息
    // let loginInfo = ref({} as {name:string,password:string})
    let loginInfo = ref({name:'',password:''})
    /**
     * 设置登录账号密码
     * @param info 登录账号密码
     */
    function setLoginInfo(info:{username:string,password:string}){
        Object.assign(loginInfo.value,info)
    }

    /**
     * 设置用户信息
     * @param info 用户信息
     */
    const setUserInfo = (info: UserInfo) => {
        userInfo.value = info
    }
    //退出系统
    const loginOut = (router: { replace: (arg0: string) => void; }) => {

        ElMessageBox.confirm(
            '是否退出?',
            '退出',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            const obj = { _gp: "admin", _mt: "logout", adminId: userInfo.value.id }
            post(obj).then(res => {
                const { errno } = res
                if (200 === errno) {
                    sessionStorage.clear()
                    localStorage.clear()
                    cookies.remove('adminToken')
                    router.replace('/login')
                    ElMessage({
                        type: 'success',
                        message: '退出成功！！',
                    })
                }
            })
        })
    }
    return { userInfo, setUserInfo, loginOut, loginInfo,setLoginInfo }
}, {
    //对个人信息持久化
    persist: {
        key: "userInfo",
        storage: window.sessionStorage,
        paths: ["userInfo"],
    },
})
export class UserInfo {
    avatarUrl: string
    gmtCreate: number
    gmtLastLogin: string
    gmtUpdate: number
    id: number
    lastLoginIp: string
    perms: Array<string>
    phone: string
    realname: string
    roleIds: Array<number>
    roles: Array<string>
    status: number
    username: string
    constructor() {
        this.avatarUrl = ""
        this.gmtCreate = 0
        this.gmtLastLogin = ""
        this.gmtUpdate = 0
        this.id = 0
        this.lastLoginIp = ""
        this.perms = []
        this.phone = ""
        this.realname = ""
        this.roleIds = []
        this.roles = []
        this.status = 0
        this.username = ""
    }
}